package com.zhangyu.shadow.repair.delegate.login;


import com.zhangyu.shadow.repair.base.IStringDataConvert;
import com.zhangyu.shadow.repair.config.ErrorMsg;
import com.zhangyu.shadow.repair.delegate.bean.LoginBean;
import com.zhangyu.shadow.repair.manager.AccountManager;

import org.greenrobot.greendao.annotation.NotNull;

import st.lib.base.account.AccountChecker;
import st.lib.base.net.callback.IError;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/5
 */
public class LoginPresenter extends LoginContract.Presenter {

    private final LoginContract.View mView;
    private final LoginContract.Model mModel;

    public LoginPresenter(@NotNull LoginContract.View view) {
        mView = view;
        mModel = new LoginModel();
    }

    @Override
    void login(String account, String password, String appId) {
        if (mView != null) {
            mView.showLoading("正在登录");
        }
        addDisposable(mModel.provideLoginData(account, password, appId
                , new IStringDataConvert<LoginBean>() {
                    @Override
                    public void convert(LoginBean loginBean) {
                        if (loginBean != null) {
                            AccountManager.getInstance()
                                    .setWorkCode(loginBean.getWorkCode())
                                    .setWorkId(loginBean.getWorkId())
                                    .setWorkName(loginBean.getWorkName())
                                    .setAuthKey(loginBean.getAuthKey())
                                    .setSourceType(loginBean.getSourceType());
                            AccountChecker.setSignState(true);
                            if (mView != null) {
                                mView.loginSuccess();
                                mView.hideLoading();
                            }
                        } else {
                            if (mView != null) {
                                mView.loginFailed(-1, ErrorMsg.ERROR_DATA);
                            }
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        if (mView != null) {
                            mView.loginFailed(code, msg);
                        }
                    }
                })
        );
    }
}
